package handler

import (
	"fcs-api/src/app/business"
	"net/http"

	"fcs-api/src/monitor"

	"github.com/emicklei/go-restful"
)

// new web service
func NewInnerHandler(handler *APIHandler) *restful.WebService {
	webServer := new(restful.WebService)
	//webServer.ApiVersion("v1")
	webServer.Path("")

	webServer.Route(
		webServer.
			GET("/metrics").
			To(handler.getMetricsMonitorData).
			Doc("prometheus pull service monitor metrics").
			Do(returns200, returns500))
	webServer.Route(
		webServer.
			GET("/prometheus").
			To(handler.getPrometheusMetricsMonitorData).
			Doc("prometheus pull service monitor metrics").
			Do(returns200, returns500))
	webServer.Route(
		webServer.GET("/healthz").
			To(handler.handleHealth))
	webServer.Route(
		webServer.GET("/report").
			To(handler.handleReportBss))
	return webServer
}

// new container
func NewWebService(webService *restful.WebService) *restful.Container {
	container := restful.NewContainer()
	container.Add(webService)
	return container
}

func returns200(b *restful.RouteBuilder) {
	b.Returns(http.StatusOK, "OK", "success")
}

func returns500(b *restful.RouteBuilder) {
	b.Returns(http.StatusInternalServerError, "server error, something went wrong", "failed")
}

func (handler *APIHandler) getMetricsMonitorData(request *restful.Request, response *restful.Response) {
	monitor.SendMetrics("fcs", false, request.Request, response)
}

func (handler *APIHandler) getPrometheusMetricsMonitorData(request *restful.Request, response *restful.Response) {
	monitor.SendPrometheusMetrics(request.Request, response)
}

func (api *APIHandler) handleHealth(request *restful.Request, response *restful.Response) {
	response.WriteHeader(http.StatusOK)
}

func (api *APIHandler) handleReportBss(request *restful.Request, response *restful.Response) {
	logger.Info("Received report Bss request")
	go func() {
		err := business.ReportDaily()
		if err != nil {
			_ = logger.Error("handleReportBss: report error, %s", err.Error())
		} else {
			logger.Info("Report to Bss success")
		}
	}()
	response.WriteHeader(http.StatusOK)
}
